export default{
	namespaced : true,
	state:()=>({
		// 购物车的数组，用来存储购物车中每个商品的信息对象
		// 每个商品的信息对象，都包含如下 6 个属性：
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cart: JSON.parse(uni.getStorageSync('cart') || '[]') 
	}),
	mutations:{
		addToCart(state,goods){
			// 返回为undefined或第一个符合的
			const findResult = state.cart.find(x=>x.goods_id===goods.goods_id)
			if(!findResult) // 如果购物车中不存在该商品，则添加
				state.cart.push(goods)
			else // 存在则计数加1
				findResult.goods_count++
			this.commit("m_cart/saveToStorage")
		},
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		updateGoodsStates(state,goods_info){
			// 注意不要写{} ，如果写了必须要写return
			const findResult = state.cart.find(x=>x.goods_id === goods_info.goods_id)
			if(findResult){
				findResult.goods_state = goods_info.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		updateGoodsCount(state,goods_info){
			const findResult = state.cart.find(x=>x.goods_id === goods_info.goods_id)
			if(findResult){
				findResult.goods_count = goods_info.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		removeGoodsItem(state,goods){
			state.cart = state.cart.filter(x=>x.goods_id !== goods.goods_id)
			this.commit('m_cart/saveToStorage')
		},
		updateGoodsState(state,newState){
			state.cart.forEach(x=>{
				x.goods_state = newState
			})
			this.commit("m_cart/saveToStorage")
		}
	},
	getters:{
		// 购物车上方动态显示(获取商品总数量)
		total(state){
			return state.cart.reduce((total,item)=> total+=item.goods_count,0)
		},
		// 获取已勾选的商品的总数量
		checkTotalCount(state){
			return state.cart.filter(x=>{
				return x.goods_state === true
			}).reduce((total,item)=>total += item.goods_count,0)
		},
		// 获取已勾选的商品的总价格
		checkedTotalPrice(state){
			return state.cart.filter(x=>{
				return x.goods_state === true
			}).reduce((total,item)=>total += item.goods_count * item.goods_price,0).toFixed(2)
		},
	}
}